package com.vf.admin.fiwork.util;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * ASCII  从小到大排序加密解密工具类
 */
public class ASCIIUtils {

    /**
     * 参数通过ascii 从小到大排序
     * @param params
     * @return
     */
    public static String ASCIIEncryption(TreeMap<String, Object> params) {
        // 方式一：TreeMap可以自动排序
        StringBuilder s1 = new StringBuilder();
        for (String key : params.keySet()) {
            // 如果参数是空值就不参加排序
            if(params.get(key) != null && params.get(key) != "" && !key.equalsIgnoreCase("sign")) {
                s1.append(key).append("=").append(params.get(key)).append("&");
            }
        }
       if(s1.length()>0){
           s1.deleteCharAt(s1.length() - 1);
       }
        return s1.toString();
    }


    /**
     * 测试 排序规则
     * @param args
     */
    public static void main(String[] args) {
        TreeMap<String,Object> params = new TreeMap<>();
        params.put("Nonce", 11886);
        params.put("Timestamp", 1465185768);
        params.put("SecretId", "AKIDz8krbsJ5yKBZQpn74WFkmLPx3EXAMPLE");
        params.put("Action", "DescribeInstances");
        params.put("Version", "2017-03-12");
        params.put("Region", "ap-guangzhou");
        params.put("Limit", 20);
        params.put("Offset", 0);
        params.put("测试", "测试");
        String s = ASCIIEncryption(params);
        System.out.println(s);
    }

}
